package com.warehouse.service.impl;

import com.warehouse.entity.Order;
import com.warehouse.entity.OrderDetail;
import com.warehouse.entity.Product;
import com.warehouse.entity.StockOut;
import com.warehouse.mapper.OrderDetailMapper;
import com.warehouse.mapper.OrderMapper;
import com.warehouse.mapper.StockOutMapper;
import com.warehouse.service.ProductService;
import com.warehouse.service.StockOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class StockOutServiceImpl implements StockOutService {

    @Autowired
    private StockOutMapper stockOutMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public List<StockOut> getAllStockOuts() {
        return stockOutMapper.selectAll();
    }

    @Override
    public StockOut getStockOutById(Long id) {
        return stockOutMapper.selectById(id);
    }

    @Override
    public List<StockOut> getStockOutsByOrderId(Long orderId) {
        return stockOutMapper.selectByOrderId(orderId);
    }

    @Override
    public List<StockOut> getStockOutsByProductId(Long productId) {
        return stockOutMapper.selectByProductId(productId);
    }

    @Override
    public List<StockOut> getStockOutsByDateRange(LocalDateTime startTime, LocalDateTime endTime) {
        return stockOutMapper.selectByDateRange(startTime, endTime);
    }

    @Override
    public List<StockOut> getStockOutsByCustomer(String customer) {
        return stockOutMapper.selectByCustomer(customer);
    }

    @Override
    public List<StockOut> getStockOutsByStatus(String status) {
        return stockOutMapper.selectByStatus(status);
    }

    @Override
    @Transactional
    public StockOut createStockOut(StockOut stockOut) {
        stockOutMapper.insert(stockOut);
        
        // 更新商品库存
        Product product = productService.getProductById(stockOut.getProductId());
        if (product != null) {
            int newQuantity = product.getStockQuantity() - stockOut.getQuantity();
            if (newQuantity >= 0) {
                productService.updateStock(stockOut.getProductId(), newQuantity);
            }
        }
        
        return stockOut;
    }

    @Override
    @Transactional
    public boolean createStockOutBatch(List<StockOut> stockOuts) {
        if (stockOuts == null || stockOuts.isEmpty()) {
            return false;
        }
        stockOutMapper.insertBatch(stockOuts);
        return true;
    }

    @Override
    @Transactional
    public boolean createStockOutFromOrder(Long orderId, String operator) {
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        // 获取订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
        if (orderDetails.isEmpty()) {
            return false;
        }

        List<StockOut> stockOuts = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetails) {
            // 检查库存是否足够
            Product product = productService.getProductById(orderDetail.getProductId());
            if (product == null || product.getStockQuantity() < orderDetail.getQuantity()) {
                return false; // 库存不足
            }

            // 创建出库记录
            StockOut stockOut = new StockOut();
            stockOut.setOrderId(orderId);
            stockOut.setProductId(orderDetail.getProductId());
            stockOut.setQuantity(orderDetail.getQuantity());
            stockOut.setUnitPrice(orderDetail.getUnitPrice());
            stockOut.setTotalAmount(orderDetail.getTotalPrice());
            stockOut.setCustomer(order.getCustomer());
            stockOut.setOperator(operator);
            stockOut.setStatus("PENDING"); // 设置为待出库状态
            stockOut.setStockOutTime(LocalDateTime.now());

            stockOuts.add(stockOut);
        }

        // 批量保存出库记录
        if (!stockOuts.isEmpty()) {
            stockOutMapper.insertBatch(stockOuts);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean updateStockOut(StockOut stockOut) {
        return stockOutMapper.update(stockOut) > 0;
    }

    @Override
    @Transactional
    public boolean processStockOut(Long stockOutId, String operator) {
        StockOut stockOut = stockOutMapper.selectById(stockOutId);
        if (stockOut == null || !"PENDING".equals(stockOut.getStatus())) {
            return false;
        }

        // 检查库存是否足够
        Product product = productService.getProductById(stockOut.getProductId());
        if (product == null || product.getStockQuantity() < stockOut.getQuantity()) {
            return false; // 库存不足
        }

        // 更新出库记录状态
        stockOut.setStatus("COMPLETED");
        stockOut.setOperator(operator);
        stockOut.setStockOutTime(LocalDateTime.now());
        stockOutMapper.update(stockOut);

        // 更新商品库存
        int newQuantity = product.getStockQuantity() - stockOut.getQuantity();
        productService.updateStock(stockOut.getProductId(), newQuantity);

        return true;
    }

    @Override
    @Transactional
    public boolean deleteStockOut(Long id) {
        return stockOutMapper.deleteById(id) > 0;
    }
} 